﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Tools
{
    public partial class TableStruct : Base
    {
        public TableStruct()
        {
            InitializeComponent();
            base.SetDefaultLocation();
        }

        string tmpHtml = @"<html xmlns=""http://www.w3.org/1999/xhtml"">
<head runat=""server"">
    <meta http-equiv=""Content-Type"" content=""text/html; charset=utf-8"" />
    <title></title>
    <style type=""text/css"">
        * { font-size: 14px; font-family: Arial 微软雅黑; }
        .table { width: 80%; border-right: 1px solid #ccc; border-bottom: 1px solid #ccc; }
        .table td { border-top: 1px solid #ccc; border-left: 1px solid #ccc; padding: 3px; line-height: 150%; }
        .table .blod { font-weight: bold; font-size: 16px; }
    </style>
</head>
<body>
    <form id=""form1"" runat=""server"">
        <table class=""table"" cellpadding=""0"" cellspacing=""0"">
             $内容$
        </table>
        <br />
        <br />
    </form>
</body>
</html>";

        private void button2_Click(object sender, EventArgs e)
        {
            Init();
        }

        public string GetConn()
        {
            var connString = string.Format("Server={0};Database={1};User ID={2};Password={3}", txt_ip.Text, txt_database.Text, txt_user.Text, txt_pwd.Text);
            if (string.IsNullOrEmpty(txt_user.Text) && string.IsNullOrEmpty(txt_pwd.Text))
            {
                connString = string.Format("Data Source={0};Initial Catalog= {1}; Integrated Security=True", txt_ip.Text, txt_database.Text);
            }
            return connString;
        }

        private void Init()
        {
            var DB = new LambdaToSql.SqlClient(new LambdaToSql.EntityModel.DbContext()
            {
                ConnectionString = GetConn(),
                SqlType = LambdaToSql.EntityModel.SqlType.MsSqlServer
            });

            var list = DB.Context.TableList.Where(ex => !ex.Name.Contains("sysdiagrams"));
            if (!string.IsNullOrEmpty(txt_filter.Text.Trim()))
            {
                list = list.Where(ex => ex.Name.Contains(txt_filter.Text.Trim())).ToList();
            }

            StringBuilder sb = new StringBuilder();
            int i = 1;
            foreach (var item in list)
            {
                sb.Append("<tr><td colspan='5' class='blod'>" + i + "、" + item.Name + "   " + item.Comments + "</td></tr>");
                sb.Append($"<tr><td>列名</td><td>字段类型(长度)</td><td>默认值(自增/主键)</td><td>字典备注</td><td>允许Null(默认否)</td></tr>");
                foreach (var column in item.Columns)
                {
                    var defaultValue = "&nbsp;";
                    if (column.IsPrimaryKey)
                    {
                        defaultValue = "主键,自增";
                    }
                    else if (!string.IsNullOrEmpty(column.DefaultValue))
                    {
                        defaultValue = column.DefaultValue;
                        defaultValue = defaultValue.ToLower().Replace("(getdate())", "getdate()").Replace("((0))", "0");
                    }
                    sb.Append($"<tr><td>{column.Name}</td><td>{column.Type}({column.Length})</td><td>{defaultValue}</td><td>{column.Comments}</td><td>{(column.IsNull ? "是" : "否")}</td></tr>");
                }
                i++;
            }
            this.webBrowser1.Document.Write(tmpHtml.Replace("$内容$", sb.ToString()));
        }

        private void btn_wiki_Click(object sender, EventArgs e)
        {
            var DB = new LambdaToSql.SqlClient(new LambdaToSql.EntityModel.DbContext()
            {
                ConnectionString = GetConn(),
                SqlType = LambdaToSql.EntityModel.SqlType.MsSqlServer
            });

            var list = DB.Context.TableList.Where(ex => !ex.Name.Contains("sysdiagrams"));

            StringBuilder sb = new StringBuilder();
            int i = 1;
            foreach (var item in list)
            {
                sb.Append("==" + item.Name + "   " + item.Comments + "==<br />");
                sb.Append("{| class=\"wikitable\"<br />");
                foreach (var column in item.Columns)
                {
                    sb.Append("|-<br />");
                    sb.Append(string.Format("| {0} || {1}<br />", column.Name, column.Comments));
                }
                sb.Append("|}<br />");
                i++;
            }

            this.webBrowser1.Document.Write("");
            this.webBrowser1.Document.Write(sb.ToString());
        }

        private void btn_er_Click(object sender, EventArgs e)
        {
            var DB = new LambdaToSql.SqlClient(new LambdaToSql.EntityModel.DbContext()
            {
                ConnectionString = GetConn(),
                SqlType = LambdaToSql.EntityModel.SqlType.MsSqlServer
            });
            var tableList = DB.Context.TableList.Where(ex => !ex.Name.Contains("sysdiagrams"));

            StringBuilder sb = new StringBuilder();

            foreach (var item in tableList)
            {
                if (item.Comments.IndexOf("弃用") < 0)
                {
                    sb.Append(string.Format("CREATE TABLE {0} {1}<br />", item.Name, item.Comments));
                    sb.Append("(<br />");

                    foreach (var column in item.Columns)
                    {
                        var type = column.Type;
                        if (type == "nvarchar")
                        {
                            type = "nvarchar(" + column.Length + ")";
                        }
                        if (column.IsIdentity)
                        {
                            sb.Append(string.Format("{0} {1} IDENTITY(1,1) NOT NULL  PRIMARY KEY {2},<br />", column.Name, type, column.Comments));
                        }
                        else
                        {
                            sb.Append(string.Format("{0} {1} NULL {2},<br />", column.Name, type, column.Comments));
                        }
                    }
                    sb.Append(");<br />");
                }
            }
            this.webBrowser1.Document.Write(sb.ToString());
        }
    }
}